#!/usr/bin/python
# -*- coding: utf-8 -*-

from flask import request, jsonify
from flask_restful import Resource, reqparse, abort, Api
from manager.models import GatePair, GatePairSchema
from gate import gateManager
from manager import gateDao

pairs_schema = GatePairSchema(many=True)
pair_schema = GatePairSchema()
parser = reqparse.RequestParser()

class GatePairResource(Resource):
    '''

    '''
    def get(self):
        '''

        :return:
        '''
        autosync = request.args.get('autosync')
        if autosync is not None:
            pair_list = gateDao.query_pairs(autosync)
        else:
            pair_list = GatePair.query.all()
        pair_list = pairs_schema.dump(pair_list).data
        return {'status': 'success', 'data': pair_list}, 200


    def post(self):
        '''

        :return:
        '''
        pair_list = gateManager.get_pair_market()
        if pair_list is None or len(pair_list) == 0:
            return {'status': 'fail', 'message': '查询失败'}, 400
        result = gateDao.insert_objects(pair_list)
        print('***********************************************************')
        if result:
            return {"status": 'success', 'data': str(result)}, 201
        else:
            return self.update_list(pair_list)



    def update_list(self,pair_list):
        successNum = 0
        failNum = 0
        for newpair in pair_list:
            if gateDao.object_merge(newpair):
                successNum += 1
            else:
                failNum += 1
        return {"status": 'success', 'data': {"success": successNum, "fail": failNum}}, 201
